package com.socket.socket.demos.socket;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.socket.socket.demos.domain.model.EnvironmentMonitor;
import com.socket.socket.demos.service.EnvironmentMonitorService;
import com.socket.socket.demos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

@Service
public class SocketService {

    @Resource
    private UserService userService;

    private final ServerSocket serverSocket;
    private Socket clientSocket = new Socket();
    @Resource
    private EnvironmentMonitorService environmentMonitorService;

    public SocketService(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    public void startServer() throws IOException {
        clientSocket = serverSocket.accept();
        //开个新线程接收消息
        new Thread(() -> {
            while (true) {
                try {
                    System.out.println("A端接收B端发送的消息Client connected: " + clientSocket.getInetAddress());
                    receiveClient(clientSocket);
                } finally {}
            }
        }).start();
    }

    private void receiveClient(Socket clientSocket) {
        try {
            // 设置客户端读取数据的超时时间
            clientSocket.setSoTimeout(60000); // 设置超时为5秒

            try (InputStream inputStream = clientSocket.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                 OutputStream outputStream = clientSocket.getOutputStream();
                 PrintWriter writer = new PrintWriter(outputStream, true)) {

                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("Received: " + line);
                    addEnvironmentMonitorInformation(line);
                    // Echo the message back to the client if necessary
                    // writer.println("Echo: " + line);
                }

            } catch (IOException e) {
                System.err.println("Error while reading from or writing to client: " + e.getMessage());
            }

        } catch (SocketException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                clientSocket.close();
                System.out.println("Closed client connection.");
            } catch (IOException e) {
                System.err.println("Error closing client connection: " + e.getMessage());
            }
        }
    }

    private void addEnvironmentMonitorInformation(String line) {
        // 解析 JSON 字符串为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(line);
        EnvironmentMonitor bean = new EnvironmentMonitor();
        // 判断是否为告警消息
        JSONArray services = jsonObject.getJSONArray("services");
        // 遍历 services 数组
        JSONObject serviceObj = (JSONObject) services.get(0);
        // 获取 properties 对象
        JSONObject properties = serviceObj.getJSONObject("properties");
        bean = JSONUtil.toBean(properties, EnvironmentMonitor.class);
        String poison = bean.getPoison();
        System.out.println(poison);
        Double poisonDouble = Double.parseDouble(poison);
        if(poisonDouble > 400){
            bean.setAlarm_level(1);
        }else {
            bean.setAlarm_level(0);
        }
        environmentMonitorService.save(bean);
    }

    public void sendClient(String flag) {
        // 开个新线程来发送消息
        new Thread(() -> {
            BufferedWriter writer = null;
            try {
                // 创建 writer 对象
                writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                String msgToSend;
                System.out.println("A端向B端发送消息 Enter message to send: ");
                // 使用 JSONUtil 创建 JSON 对象
                JSONObject jsonObject = new JSONObject();

                // 创建 properties JSON 对象
                JSONObject properties = new JSONObject();

                // 根据 doorStatus 设置 onoff 的值
                if (flag.contains("door")){
                    jsonObject.set("command_name", "door_control");
                    if("door1".equals(flag)){
                        properties.set("onoff", "ON");
                    }else{
                        properties.set("onoff", "OFF");
                    }
                }
                if (flag.contains("light")){
                    jsonObject.set("command_name", "light_control");
                    if("light1".equals(flag)){
                        properties.set("onoff", "ON");
                    }else{
                        properties.set("onoff", "OFF");
                    }
                }
                if (flag.contains("motor")){
                    jsonObject.set("command_name", "motor_control");
                    if("motor1".equals(flag)){
                        properties.set("onoff", "ON");
                    }else{
                        properties.set("onoff", "OFF");
                    }
                }
                // 将 properties 对象设置到 jsonObject 中
                jsonObject.set("properties", properties);

                // 输出 JSON 字符串
                System.out.println(jsonObject.toString());
                msgToSend = jsonObject.toString();
                if (msgToSend != null && !msgToSend.isEmpty()) {
                    writer.write(msgToSend);
                    writer.newLine();
                    writer.flush();
                    System.out.println("A端已发送消息: " + msgToSend);  // 输出已发送的消息，确认发送成功
                }

            } catch (IOException e) {
                System.err.println("Error while sending message: " + e.getMessage());
            }finally {
                // 线程结束
                System.out.println("消息发送线程已结束");
            }
        }).start();
    }
    public void sendClientInformation(String str) {
        // 开个新线程来发送消息
        new Thread(() -> {
            BufferedWriter writer = null;
            try {
                // 创建 writer 对象
                writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                String msgToSend;
                System.out.println("A端向B端发送消息 Enter message to send: ");
                // 输出 JSON 字符串
                System.out.println(str);
                msgToSend = str;
                if (msgToSend != null && !msgToSend.isEmpty()) {
                    writer.write(msgToSend);
                    writer.newLine();
                    writer.flush();
                    System.out.println("A端已发送消息: " + msgToSend);  // 输出已发送的消息，确认发送成功
                }

            } catch (IOException e) {
                System.err.println("Error while sending message: " + e.getMessage());
            }finally {
                // 线程结束
                System.out.println("消息发送线程已结束");
            }
        }).start();
    }
}

